//
//  UITableView + headerZoom.swift
//  YKZoomHeaderView
//
//  Created by YK on 16/2/16.
//  Copyright © 2016年 YK. All rights reserved.
//

import UIKit

extension UITableView {
    
    func addZoomHeaderView(headerView:UIView) {
        self.contentInset = UIEdgeInsetsMake(headerView.frame.size.height, 0, 0, 0)
        headerView.tag = 10000;
        headerView.frame = CGRectMake(0, -headerView.frame.size.height, headerView.frame.size.width, headerView.frame.size.height)
        self.addSubview(headerView)
        self.addObserver(self, forKeyPath: "contentOffset", options: .New, context: nil)
    }
    
    public override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        let offsetY = object?.contentOffset.y
        if(offsetY < -self.contentInset.top){
            self.changeFrame(offsetY!)
        }
    }
    
    private func changeFrame(offsetY:CGFloat) {
        let  headerView = self.viewWithTag(10000)
        var frame = headerView!.frame
        frame.origin.y = offsetY
        frame.size.height = -offsetY
        frame.origin.x = offsetY + self.contentInset.top
        frame.size.width = self.frame.size.width + 2 * -frame.origin.x
        headerView?.frame = frame
    }
    
}